package library;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import user_client.NormalUserClient;



public class UserChangePasswordPane extends GuiTemplatePane {
	
	private TextPane infoEntry = null;
	private ChangePasswordPane changePane = new ChangePasswordPane();
	private NormalUserClient client;
	
	
	public UserChangePasswordPane(JPanel mainArea, NormalUserClient client) {
		
		super(mainArea,"change password");
		this.client = client;
		this.setEntity(changePane);
	}
	
	private class ChangePasswordPane extends JPanel{
		
		public ChangePasswordPane() {
			this.setLayout(new BorderLayout());
			String[] names = new String[3];
			names[0] = "old password: ";
			names[1] = "new password: ";
			names[2] = "new password again: ";
			
			infoEntry = new TextPane(names, new JPasswordField(), 
					new JPasswordField(), new JPasswordField());
			
			this.add(infoEntry, BorderLayout.CENTER);
			JPanel decisionPanel = new JPanel(new GridLayout(1, 2));
			JButton changePass = new JButton("change password");
			changePass.addActionListener(new ChangePasswordActionListener());
			JButton abort = new JButton("abort");
			abort.addActionListener(new AbortPasswordEditorActionListener());
			decisionPanel.add(changePass);
			decisionPanel.add(abort);
			this.add(decisionPanel, BorderLayout.SOUTH);
		}
		
		private class ChangePasswordActionListener implements ActionListener {

			@Override
			public void actionPerformed(ActionEvent e) {
				JPasswordField oldPass = (JPasswordField) infoEntry.getField("old password: ");
				JPasswordField newPass = (JPasswordField) infoEntry.getField("new password: ");
				JPasswordField newPassAgain = (JPasswordField) infoEntry.getField("new password again: ");
				String oldPassText = String.valueOf(oldPass.getPassword());
				String newPassText = String.valueOf(newPass.getPassword());
				String newPassAgainText = String.valueOf(newPassAgain.getPassword());
				
				if (newPassAgainText.equals(newPassText)){
					try {
						client.changePassword(oldPassText , newPassText );
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
						System.out.println(e1.getMessage());
					}
				} else {
					newPassAgain.setText("");
					newPass.setText("");
				}
			}

		}

		
		
		private class AbortPasswordEditorActionListener implements ActionListener {

			@Override
			public void actionPerformed(ActionEvent e) {
				
				UserChangePasswordPane.this.getMainArea().removeAll();	
				UserChangePasswordPane.this.getMainArea().repaint();
			}
		}
	}
}
